const userDao = require('../userDao')
const jwtToken = require('../jwt')
const mysqlConnection = require('../db/index')
const bcryptUtils = require('../utils/bcrypt')
function handleSignIn(req, res) {
  userDao
    .onSelectOnlyUser(req.body)
    .then((result) => {
      if (result.length === 0 || result.length >= 2) {
        res.rendStatus({ status: 201, data: result })
      } else {
        let data = result[0]
        let authorization = jwtToken.encrypt({ data: res.userid })
        res['authorization'] = authorization
        res.rendStatus({ data: data })
      }
    })
    .catch((err) => {
      res.rendStatus({ status: 500, err })
    })
}

function handleSignUp(req, res) {
  res.send('登录成功')
  res.rendStatus({ msg: '登录成功' })
}

function handleTest(req, res) {
  try {
    res.rendStatus({ msg: 'hello' })
  } catch (error) {
    console.log('错误信息', error)
    res.send(error)
  }
}

function handleUserInfo(req, res) {
  try {
    // res.send('用户信息')
    // const sql = `select * from user where userid = '${req.params.userid}'`
    console.log(req.auth)
    const selectSql =
      'SELECT userid,username,email,createtime,updatetime FROM user WHERE userid = ? '
    const selectSqlParams = [req.auth.data]
    mysqlConnection.query(selectSql, selectSqlParams, function (err, result) {
      if (err) {
        res.rendStatus({ status: 500, err: '获取用户信息失败' })
        return
      }
      if (result.length === 0) {
        res.rendStatus({ status: 500, err: '获取用户信息失败' })
        return
      }
      res.rendStatus({ msg: '获取用户信息成功', data: result[0] })
    })
  } catch (error) {
    res.rendStatus({ status: 500, err: '获取用户信息失败' })
  }
}

function handleLogin(req, res) {
  const selectSql = 'SELECT password,userid FROM user WHERE userName = ?'
  const selectSqlParams = [req.body.userName]
  mysqlConnection.query(selectSql, selectSqlParams, function (err, result) {
    if (err) {
      res.rendStatus({ status: 500, err: '失败' })
      return
    }
    if (result.length === 0) {
      res.rendStatus({ status: 500, err: '失败' })
      return
    }

    console.log('req.body', req.body)

    let userInfo = result[0]
    console.log('userInfo', userInfo)

    bcryptUtils
      .encryptCompare(req.body.password, userInfo.password)
      .then((result) => {
        console.log('resultresultresult', result)
        if (result === true) {
          let authorization = jwtToken.encrypt({ data: userInfo.userid })
          userInfo['authorization'] = authorization
          res.rendStatus({ msg: '登录成功', data: userInfo })
        } else {
          res.rendStatus({ status: 500, err: '密码错误' })
        }
      })
      .catch((err) => {
        res.rendStatus({ status: 500, err })
      })

    // const selectSql =
    //   'SELECT userid,username,email,createtime,updatetime,password FROM user WHERE userName = ?'
    // const selectSqlParams = [req.body.userName]

    // mysqlConnection.query(selectSql, selectSqlParams, function (err, result) {
    //   if (err) {
    //     res.rendStatus({ status: 500, err: '登录失败' })
    //     return
    //   }
    //   if (result.length === 0) {
    //     res.rendStatus({ status: 500, err: '登录失败' })
    //     return
    //   }

    //   let userInfo = result[0]
    //   console.log('userInfo', userInfo)
    //   bcryptUtils
    //     .encryptCompare(req.body.password, userInfo.password)
    //     .then((res) => {
    //       console.log('res', res)

    //       if (res === true) {
    //         let authorization = jwtToken.encrypt({ data: userInfo.userid })
    //         userInfo['authorization'] = authorization
    //         res.rendStatus({ msg: '登录成功', data: userInfo })
    //       } else {
    //         res.rendStatus({ status: 500, err: '登录失败' })
    //       }
    //     })
    //     .catch((err) => {
    //       res.rendStatus({ status: 500, err })
    //     })
    // })
  })
}

function handleRegister(req, res) {
  const selectSql = 'SELECT userid FROM user WHERE userName = ?'
  const selectSqlParams = [req.body.userName]
  mysqlConnection.query(selectSql, selectSqlParams, function (err, result) {
    if (err) {
      res.rendStatus({ status: 500, err: '失败' })
      return
    }
    if (result.length > 0) {
      res.rendStatus({ status: 500, err: '用户名已被人使用，请更换其他用户名' })
      return
    }
    let createtime = new Date()
    let updatetime = createtime
    console.log('req.body.password', req.body.password)
    bcryptUtils
      .encrypt('' + req.body.password)
      .then((encryptedPassword) => {
        console.log('encryptedPassword', encryptedPassword)
        const selectSql =
          'INSERT INTO user ( username, password,email,createtime,updatetime ) VALUES (?, ?,?,?,?)'
        const selectSqlParams = [
          req.body.userName,
          encryptedPassword,
          req.body.email,
          createtime,
          updatetime
        ]
        mysqlConnection.query(selectSql, selectSqlParams, function (err, result) {
          if (err) {
            res.rendStatus({ status: 500, err })
            return
          }
          if (result.affectedRows === 1) {
            res.rendStatus({ msg: '注册成功', data: 'userInfo' })
            return
          } else {
            res.rendStatus({ status: 500, err: '注册失败' })
          }
        })
      })
      .catch((err) => {
        return res.rendStatus({ status: 500, err: '注册失败' })
      })
  })
}

module.exports = {
  handleSignIn,
  handleSignUp,
  handleTest,
  handleUserInfo,
  handleLogin,
  handleRegister
}
